/*
 * Copyright 2020-2021 the original author(https://github.com/wj596)
 *
 * <p>
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *     http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 * </p>
 */

package global

import (
	"context"
	"github.com/gogf/gf/v2/os/glog"
	"runtime"
	"strconv"
	"syscall"
	"time"
)

var (
	_pid         int
	_leaderFlag  bool
	_leaderNode  string
	_currentNode string
	_bootTime    time.Time
)

func SetLeaderFlag(flag bool) {
	_leaderFlag = flag
}

func IsLeader() bool {
	return _leaderFlag
}

func SetLeaderNode(leader string) {
	_leaderNode = leader
}

func LeaderNode() string {
	return _leaderNode
}

func CurrentNode() string {
	return _currentNode
}

func IsFollower() bool {
	return !_leaderFlag
}

func BootTime() time.Time {
	return _bootTime
}

func Initialize(ctx context.Context) error {
	if err := initConfig(ctx); err != nil {
		return err
	}

	runtime.GOMAXPROCS(_config.Maxprocs)

	_bootTime = time.Now()
	_pid = syscall.Getpid()

	glog.Printf(ctx, "process id: %d", _pid)
	glog.Printf(ctx, "GOMAXPROCS :%d", _config.Maxprocs)
	glog.Printf(ctx, "source  %s(%s)", _config.Flavor, _config.Addr)
	glog.Printf(ctx, "destination %s", _config.Destination())

	return nil
}

func InitializeCluster() {
	if _config.IsCluster() {
		if _config.EnableWebAdmin {
			_currentNode = _config.Cluster.BindIp + ":" + strconv.Itoa(_config.WebAdminPort)
		} else {
			_currentNode = _config.Cluster.BindIp + ":" + strconv.Itoa(_pid)
		}
	}
}
